package com.jihox.abookpro;


import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jihox.abookpro.domain.BookProject;
import com.jihox.abookpro.domain.ImageInfo;
import com.jihox.abookpro.domain.Page;
import com.jihox.abookpro.domain.PagePicture;
import com.jihox.abookpro.domain.PictureHolder;
import com.jihox.abookpro.util.NativeImageLoader;
import com.jihox.abookpro.util.PictureUtil;
import com.jihox.abookpro.view.ZoomImageView;
import com.lightbox.android.photoprocessing.PhotoProcessingActivity;

public class SinglePageEditActivity extends BaseActivity {
	
	private String outputpath = null;
	public BookProject bookProject;
	protected ArrayList<ZoomImageView> zoomViewList;
	private int selectpic;	
	private int mPageNum = -1;
	private int mPictureNum = -1;
	private static final int REQUEST_CODE_REPLACE_PICTURE = 0x100001;
	private static int REQUEST_CODE_EDIT_PICTURE = 11020201;
	private Page edpage;
	private int imageWidth = 0;
	private int imageHeight = 0;
	private int mindex;
	private Bitmap backgroundBitmap;
	private int category;
	private RelativeLayout image_popup_layout;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);         
        /*set it to be full screen*/ 
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,    
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.image_edit_popup);
		
		Intent intent = getIntent();
		mPageNum = intent.getIntExtra("mPageNum", 0);
		mPictureNum = intent.getIntExtra("mPictureNum", 0);
		mindex = intent.getIntExtra("mindex", 0);
		imageWidth = intent.getIntExtra("imageWidth", 0);
		imageHeight = intent.getIntExtra("imageHeight", 0);
		bookProject = (BookProject) intent.getSerializableExtra("bookProject");
		edpage = bookProject.getBook().getPages().get(mPageNum);
		category = intent.getIntExtra("category", 0);
		backgroundBitmap = loadBitmapWithCache(500,500,mPageNum);
		if(category == 2){
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		}else{
			if(this.getResources().getConfiguration().orientation ==Configuration.ORIENTATION_PORTRAIT){
				   setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			}
		}
						
		image_popup_layout = (RelativeLayout) findViewById(R.id.image_popup_rl);
        Button btn_apply = (Button) findViewById(R.id.btn_apply);
        Button btn_cancle = (Button) findViewById(R.id.btn_cancle);
        Button btn_deluxe = (Button) findViewById(R.id.btn_deluxe);
        Button btn_replace = (Button) findViewById(R.id.btn_replace);
                    
        btn_apply.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				Page page = bookProject.getBook().getPages().get(mPageNum);
				List<PagePicture> list = new ArrayList<PagePicture>();
				int b = 0;
				for(int i=0;i<page.getPictures().size();i++){
					if(page.getPictures().get(i).isClipart()){
						list.add(page.getPictures().get(i));
					}else{
						PagePicture pagePicture = zoomViewList.get(b).getPagePicture();
						list.add(pagePicture);
						if (!PictureUtil.isSuitablePicture(
								bookProject.getBook().getProduct().getDpiOfPicture(),pagePicture) && pagePicture.getImage().isQualified()) {
								showDialog();
							return;
						}
						b++;
					}
				}

				bookProject.getBook().getPages().get(mPageNum).setPictures(list);					
				page.setNeedRedraw(true);
				
				Intent data = new Intent();
				data.putExtra("bookProject", bookProject);
				setResult(Activity.RESULT_OK, data);
				finish();
			}
		});
        //取消popupwindow
        btn_cancle.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
        //照片高级编辑
        btn_deluxe.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {

				String mPicturePath = edpage.getPictures().get(mPictureNum).getImage().getPath();
				
				if(mPicturePath!=null || !mPicturePath.isEmpty()){
							Intent intent = new Intent(SinglePageEditActivity.this,PhotoProcessingActivity.class);
							intent.putExtra("imagepath", mPicturePath);
							startActivityForResult(intent, REQUEST_CODE_EDIT_PICTURE);
					
				}else{
					Toast.makeText(SinglePageEditActivity.this, "获取图片路径失败", Toast.LENGTH_SHORT).show();
				}
				
			}
		});
        //替换照片
        btn_replace.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		        startActivityForResult(intent, REQUEST_CODE_REPLACE_PICTURE);
			}
		});
        
        if (mPageNum % 2 != 0){
        	Matrix matrix = new Matrix();
        	float[] values = { -1f, 0.0f, 0.0f, 0.0f, 1f, 0.0f,
        			0.0f, 0.0f, 1.0f };
        	matrix.setValues(values);
        	backgroundBitmap = Bitmap.createBitmap(backgroundBitmap, 0, 0,
        			backgroundBitmap.getWidth(),
        			backgroundBitmap.getHeight(), matrix, true);
        }
        showPage();
        
	}
	
	private void showPage(){
        image_popup_layout.setBackgroundDrawable(new BitmapDrawable(backgroundBitmap));

        imageHeight = (int) (imageWidth * edpage.getHeight()/edpage.getWidth());
        RelativeLayout.LayoutParams rl_image_popup_params = new RelativeLayout.LayoutParams(imageWidth,imageHeight);
        rl_image_popup_params.addRule(RelativeLayout.CENTER_IN_PARENT);
        image_popup_layout.setLayoutParams(rl_image_popup_params);
       
        int pictureCnt = 0;
        selectpic = mPictureNum;//记录当前选中照片
        zoomViewList = new ArrayList<ZoomImageView>();
        final List<RelativeLayout> rlList = new ArrayList<RelativeLayout>();//记录imageview外的relativelayout
        for (PagePicture pagePicture :  edpage.getPictures()){
        	if (pagePicture.isClipart()){
        		continue;
        	}
        	//照片大小和位置
        	RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int) Math.ceil(pagePicture.getHolder().getWidth()*imageWidth/edpage.getWidth()+1), 
             		(int) Math.ceil(pagePicture.getHolder().getHeight()*imageHeight/edpage.getHeight())+1);
        	params.setMargins(2,2,0,0);
            //照片外的layout照片框的大小和位置
            RelativeLayout.LayoutParams rlparams = new RelativeLayout.LayoutParams((int) Math.ceil(pagePicture.getHolder().getWidth()*imageWidth/edpage.getWidth()+5), 
             		(int) Math.ceil(pagePicture.getHolder().getHeight()*imageHeight/edpage.getHeight())+5);
            rlparams.setMargins((int)(pagePicture.getHolder().getX()*imageWidth/edpage.getWidth())-2, (int)(pagePicture.getHolder().getY()*imageHeight/edpage.getHeight())-2, 0, 0);
            ZoomImageView imageView = null;
            //初始化添加的view
        	View view = LayoutInflater.from(SinglePageEditActivity.this).inflate(
					R.layout.zoom_image_layout, null);
        	final RelativeLayout rlim = (RelativeLayout) view.findViewById(R.id.image_rl);
        	imageView = (ZoomImageView) view
					.findViewById(R.id.zoom_image_view);

            rlim.setLayoutParams(rlparams);
            imageView.setLayoutParams(params);

            imageView.setBackgroundColor(Color.WHITE);
        	imageView.setImageBitmap(NativeImageLoader.getInstance()
     				.loadNativeImageSync(pagePicture.getImage().getPath().trim(),
     						null, false),pagePicture);
        	if(pictureCnt==selectpic){//如果照片为选中照片，则选中照片可以进行缩放，照片框变为红色表示选中
        		imageView.setMove(true);
        		if (pagePicture.getHolder().getMaskPath()==null || pagePicture.getHolder().getMaskPath().isEmpty()){
        			rlim.setBackgroundColor(Color.RED);
        		}
			}else{//否则照片框禁止掉touch事件以便触发照片框的点击事件，照片框隐藏
				imageView.setMove(false);
				rlim.setBackgroundColor(Color.TRANSPARENT);			
			}
        	rlim.setTag(pictureCnt);//将照片号设置到对应的照片框中
        	rlim.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					selectpic = Integer.parseInt(rlim.getTag().toString());//更改当前选中照片
					for(int i=0;i<rlList.size();i++){
						if(i==selectpic){//选中照片的照片框变为红色
							mPictureNum = selectpic;
							zoomViewList.get(i).setMove(true);
							if (edpage.getPictures().get(mPictureNum).getHolder().getMaskPath()==null || 
									edpage.getPictures().get(mPictureNum).getHolder().getMaskPath().isEmpty()){
								rlList.get(i).setBackgroundColor(Color.RED);
							}
						}else{//其他隐藏
							zoomViewList.get(i).setMove(false);
							rlList.get(i).setBackgroundColor(Color.TRANSPARENT);				
						}
					}
				}
			});
        	rlList.add(rlim);
     		zoomViewList.add(imageView);
 			image_popup_layout.addView(rlim);
     		pictureCnt++;
        }
	}
	
	//替换或修改照片后，更新
	private PagePicture updateEditPhoto(String outpath,int pagNum,int picNum,int mindex){
		Page page = bookProject.getBook().getPages().get(pagNum);
    	PictureHolder holder = page.getPictures().get(picNum).getHolder();
    	
    	PagePicture pagPicture = new PagePicture();
    	pagPicture.setHolder(holder);
    	ImageInfo mimageInfo = new ImageInfo();
    	
    	mimageInfo.setPath(outpath);
    	BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(outpath, options);
    
		int degree = PictureUtil.readPictureDegree(outpath);
		float imageHeight =0;
		float imageWidth = 0;
		if (degree == 90 || degree == 270) {
			imageHeight = options.outWidth;
			imageWidth = options.outHeight;
		}else{
			imageHeight = options.outHeight;
			imageWidth = options.outWidth;
		}
		
		float heightRatio = holder.getHeight()/imageHeight;
		float widthRatio = holder.getWidth()/imageWidth;
		
		if (heightRatio > widthRatio ) {
			float height = holder.getHeight();
			float width = imageWidth * (float)(height/imageHeight);
			mimageInfo.setWidth(width);
			mimageInfo.setHeight(height);
			mimageInfo.setX((holder.getWidth() - width)/2);
			mimageInfo.setY(0);
		} else {
			float width = holder.getWidth();
			float height = imageHeight * width
					/ imageWidth;
			mimageInfo.setWidth(width);
			mimageInfo.setHeight(height);
			mimageInfo.setX(0);
			mimageInfo.setY((holder.getHeight()- height)/2);
		}
		pagPicture.setImage(mimageInfo);

		return pagPicture;
	}
	
	
	private void showDialog() {
		
		 final Dialog dialog = new Dialog(SinglePageEditActivity.this, R.style.JHDialog);
        //设置它的ContentView
        dialog.setContentView(R.layout.dialog_general);
        Button buttonOK = (Button) dialog.findViewById(R.id.dialog_button_ok);
        Button buttonCancel = (Button) dialog.findViewById(R.id.dialog_button_cancel);
        TextView dialogTitle = (TextView) dialog.findViewById(R.id.dialog_title);
        TextView dialogMessage = (TextView) dialog.findViewById(R.id.dialog_message);
        
        buttonOK.setBackgroundResource(R.drawable.green_style);
        buttonCancel.setBackgroundResource(R.drawable.grey_style);
        buttonOK.setText(R.string.T_Select_Still);
        buttonCancel.setText(R.string.T_Cancel);
        dialogTitle.setText(R.string.T_Warning_Text);
        dialogMessage.setText(R.string.T_Photo_Size_Small);
        
        buttonOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				Page page = bookProject.getBook().getPages().get(mPageNum);
				List<PagePicture> list = new ArrayList<PagePicture>();
				int b = 0;
				for(int i=0;i<page.getPictures().size();i++){
					if(page.getPictures().get(i).isClipart()){
						list.add(page.getPictures().get(i));
					}else{
						PagePicture pagePicture = zoomViewList.get(b).getPagePicture();
						list.add(pagePicture);
						b++;
					}
				}
				
				bookProject.getBook().getPages().get(mPageNum).setPictures(list);					
				page.setNeedRedraw(true);
				
				Intent data = new Intent();
				data.putExtra("bookProject", bookProject);
				setResult(Activity.RESULT_OK, data);
				finish();
				
			}
		});
       buttonCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
        
        dialog.show();
	}
	
	
	// 处理startActivityForResult的回调函数
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_REPLACE_PICTURE
                && resultCode == Activity.RESULT_OK
                && null != data) {//替换照片
			
            Uri selectedImage = data.getData();
            if(selectedImage.getScheme().toString().compareTo("file")==0){
            	outputpath = selectedImage.toString().replace("file://", "");
            }else{
	            String[] filePathColumns = new String[]{MediaStore.Images.Media.DATA};
	            Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
	            c.moveToFirst();
	            int columnIndex = c.getColumnIndex(filePathColumns[0]);
	            outputpath = c.getString(columnIndex);
	            c.close();
            }
            
//	            Log.i("msg_p_path", mPicturePath);
            if (null != outputpath) {
            	
            	Bitmap mbitmap = PictureUtil.decodeFileThumb(SinglePageEditActivity.this, outputpath);
            	           	
            	PagePicture pp = updateEditPhoto(outputpath, mPageNum, mPictureNum, mindex);
            	int degree = PictureUtil.readPictureDegree(outputpath);
				mbitmap = PictureUtil.rotateBitmap(mbitmap, degree);
//					zoomViewList.get(mPictureNum).setImageBitmap(mbitmap,pp);
				int j=0;
				for(int i=0;i<edpage.getPictures().size();i++){
					if(edpage.getPictures().get(i).isClipart()){
						continue;
					}
					if(i == mPictureNum){
						edpage.getPictures().set(i, pp);
					}else{
						edpage.getPictures().get(i).setHolder(zoomViewList.get(j).getPagePicture().getHolder());
					}
					j++;
				}
				
				showPage();
            }

            return;
        }else if(requestCode == REQUEST_CODE_EDIT_PICTURE && resultCode == RESULT_OK){//编辑照片
				
				outputpath =  data.getStringExtra("editImagePath");;
				
				PagePicture pp = updateEditPhoto(outputpath, mPageNum, mPictureNum , mindex);//刷新
				int j=0;
				for(int i=0;i<edpage.getPictures().size();i++){
					if(edpage.getPictures().get(i).isClipart()){
						continue;
					}
					if(i == mPictureNum){
						edpage.getPictures().set(i, pp);
					}else{
						edpage.getPictures().get(i).setHolder(zoomViewList.get(j).getPagePicture().getHolder());
					}
					j++;
				}
				showPage();
        }
	}
	
	public Bitmap loadBitmapWithCache(int width, int height, int index) {
		Bitmap bitmap = null;		
		bitmap = NativeImageLoader.getInstance()
				.loadNativeImageSyncAndOriginal(getImagePath(index),
						false);		
		
		return bitmap;
	}
							
	private String getDirPath() {
		return Environment.getExternalStorageDirectory()
				+ NativeImageLoader.jihoxUrl + "/.album";
	}

	private String getImagePath(int index) {
		return getDirPath() + "/albumpage" + index + ".jpg";
	}

	
	
	
	
	
}
